(function(w){

      Date.prototype.Format = function (fmt) { // author: meizz
      
        var o = {
            "M+": this.getMonth() + 1, // 月份
            "d+": this.getDate(), // 日
            "h+": this.getHours(), // 小时
            "m+": this.getMinutes(), // 分
            "s+": this.getSeconds(), // 秒
            "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
            "S": this.getMilliseconds() // 毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                return fmt;

      }

      var linxi = {

        layer:layui.layer,
        form : layui.form,
        table: layui.table,
        starDate:new Date().Format('yyyy-MM-dd 00:00:00'),
        endDate:new Date().Format('yyyy-MM-dd 23:59:59'),
        nowDate:new Date().Format('yyyy-MM-dd hh:mm:ss'),
        init:function(){  //初始化

          var self = this

        },
        createTable:function(parmsObj,ele,fileds,page=false){

            var table=layui.table

            var self =this

            //第一个实例客服维度的报表
            table.render({

              elem: ele
              ,url: '../api/api.php'+self.createUrlParse(parmsObj) //数据接口
              ,page: page //开启分页
              ,cols: [fileds]
            });


            return table



        },
        laydate:function(ele,fun){  //选择日期并回调刷新表格

          //第一个参数为 日期input元素的id
          //第二个参数为 要进行更新的表格的集合格式为 [{'ele':'表格元素的id'},{}......]
          //第三个参数为 要进行GET的传递的参数集合格式为 {'参数key':'参数val','':'',....}
          var laydate = layui.laydate

          var table = layui.table

          var self = this

          //执行一个laydate实例
          laydate.render({
             elem: ele //指定元素
            ,range:true
            ,type:'datetime'
            ,value:new Date().Format('yyyy-MM-dd 00:00:00')+ ' - '+new Date().Format('yyyy-MM-dd 23:59:59')
            ,done: function(value, date, endDate){

              // console.log(value); //得到日期生成的值，如：2017-08-18
              // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
              // console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
              // dateRange = value.split(' - ').join("&endDate=")
              // console.log(dateRange)
              fun(value, date, endDate)
              

            }
          });

        },
        getFormSelectLevelSql:function(level){

          // var level = $(ele).val();

          if(level==0){
              return filter = "('591-lx','test-lx')"
          }else if(level==1){
            return filter = "('591-lx')"
          }else if(level==2){
            return filter = "('test-lx')"
          }
      
        },
        download_file:function (data){
          //获取当前域名
          var domain = document.domain + '\\林西项目\\api\\'+data;

          window.location.href = "http://"+domain;
          // download("http://"+domain+"/file.txt","file.txt","text/plain");
        },
        laySelect:function(filter,tableEle,parmsObj){

          var self = this

          this.form.on('select(level)', function(data){ //选择AB库
              // console.log(data.elem); //得到select原始DOM对象
              // console.log(data.value); //得到被选中的值
              // console.log(data.othis); //得到美化后的DOM对象

              parmsObj['starDate'] = $('#date1').val().split(' - ')[0]
              parmsObj['endDate'] = $('#date1').val().split(' - ')[1]
              parmsObj['userLevel'] = data.value
              parmsObj['ABku'] = self.getFormSelectLevelSql(data.value)
              console.log(data.value)

              self.table.reload(tableEle, {
                url: '../api/api.php'+self.createUrlParse(parmsObj)
              });

  
          });

        },
        importExcel:function(parseData){

        },
        createUrlParse:function(parmsObj){  //通过对像生成请求参数链接
           urlparm = ''
            var n = 0
            for(var key in parmsObj){
              if (n==0){
                urlparm+='?'+key+'='+parmsObj[key]
              }else{
                urlparm+='&'+key+'='+parmsObj[key]
              }
              n+=1
            }
          return urlparm
        },
        clickRowEvent:function(filter,fun){//单击行显示客资的详情


          var table = layui.table
          
          //监听行单击事件
          table.on('row('+filter+')', function(obj){

            // console.log(obj.tr) //得到当前行元素对象
            // console.log(obj.data) //得到当前行数据

            fun(obj)

          });
        },
        showRemark:function(obj){ //显示备注详情

          
          var self = this
          var layer =  layui.layer

          self.getbyremark(obj.data.customerId,function(remark){


              var code = JSON.parse(remark)['code']

              if(code == 400){

                layer.msg('请联系帅帅，进行设置 手机号码：18801263882');
                return

              }

              var remark = JSON.parse(remark).data.list

              console.log(remark)

              console.log(obj.data)

              
              if(obj.data.Reasons_for_disqualification!==undefined){

                if(obj.data.Reasons_for_disqualification!==null){

                    if(obj.data.Reasons_for_disqualification.length !== 0  ){

                      $Reasons_for_disqualification = `<div class="layui-form-item" >
                                  <label class="layui-form-label">备注：</label>
                                  <div class="layui-input-block">
                                    <div class="layui-input copytext" style="line-height:38px;" id="Reasons_for_disqualification">${obj.data['Reasons_for_disqualification']}</div>
                                  </div>
                      </div>`

                    }else{

                      $Reasons_for_disqualification =''
                    }


                }else{

                  $Reasons_for_disqualification = ``

                }

              }else{

                  $Reasons_for_disqualification = ``

              }

              

              $html = `

                      <div class="layui-card">
                          <div class="layui-card-header">基本信息</div>
                          <div class="layui-card-body">
                              <div class="layui-form-item" >
                                <label class="layui-form-label">客户姓名：</label>
                                <div class="layui-input-block">
                                  <div class="layui-input copytext" id="contactName" style="line-height:38px;">${obj.data['contactName']}</div>
                                </div>
                              </div>
                              <div class="layui-form-item" >
                                <label class="layui-form-label">手机号码：</label>
                                <div class="layui-input-block">
                                  <div class="layui-input copytext" id="mobile" style="line-height:38px;">${obj.data['mobile']}</div>
                                </div>
                              </div>
                              ${$Reasons_for_disqualification}
                        </div>
                      </div>`

              followUserNames=[]//放播打电话客服的数组

              for(var i =0; i < remark.length ; i++){

                  var remarkStr = remark[i]['remark']==null?'无备注':remark[i]['remark']

                  var luyinOssUrl = remark[i]['luyinOssUrl']

                  if(luyinOssUrl==null){

                    var luyinOssUrl = ``
                    
                  }else{


                    var luyinOssUrl = `<div class="layui-form-item">
                          <label class="layui-form-label">通话ID：</label>
                          <div class="layui-input-block">
                            <div class="layui-input copytext" id="callInstanceId${i}" style="line-height:38px;">${remark[i]['callInstanceId']}</div>
                          </div>
                          <label class="layui-form-label">录音：</label>
                          <div class="layui-input-block">
                            <audio style="width:100%; margin-top:50px;" controls src="${remark[i]['luyinOssUrl']}"></audio>
                          </div>
                      </div>`

                  }

                  followUserNames.indexOf(remark[i]['followUserName'])==-1?remark[i]['followUserName']!==null?followUserNames.push(remark[i]['followUserName']):'':'' 
                  
                  $html +=`
                  <div class="layui-card">
                    <div class="layui-card-header">第${remark.length - i}次沟通</div>
                    <div class="layui-card-body">

                        <div class="layui-form-item">
                          <label class="layui-form-label">沟通时间：</label>
                          <div class="layui-input-block">
                            <div class="layui-input copytext" id="gmtCreate${i}" style="line-height:38px;">${remark[i]['gmtCreate']}</div>
                          </div>
                        </div>

                        <div class="layui-form-item">
                          <label class="layui-form-label">沟通客服：</label>
                          <div class="layui-input-block">
                            <div class="layui-input copytext" id="followUserName${i}" style="line-height:38px;">${remark[i]['followUserName']}</div>
                          </div>
                        </div>

                        <div class="layui-form-item">
                          <label class="layui-form-label">备注：</label>
                          <div class="layui-input-block">
                            <p style="line-height:38px;" class="copytext" id="remarkStr${i}">
                              ${remarkStr}   
                            </p>
                          </div>
                        </div>
                        ${luyinOssUrl}
                    </div>
                  </div>`
              }

              var hrefs = window.location.href.split("/") //获取当前页面名称

              var pageName = hrefs[hrefs.length-1].split(".")[0]

              console.log(pageName)

              if(self.userInfo.data.titleId=='QC' && pageName == 'table'){

                msgObj={

                  type: 1,
                  btn: ['分配', '不合格'],
                  skin: 'layui-layer-rim', //加上边框
                  area: ['60%', '80%'], //宽高
                  content: $html,
                  title:'沟通信息',
                  shadeClose:true,
                  
                  yes:function(index,layero){

                    var statusId = 1

                    this.parseData['statusId']=statusId

                    self.QC_updateFollowUserName(this.parseData)
                  },
                  btn2:function(index,layero){

                    var statusId = 0

                    this.parseData['statusId']=statusId

                    self.QC_updateFollowUserName(this.parseData)
                  },
                  parseData:{ 

                        type:'updata_customer_yunweinames_status',
                        statusId:statusId,
                        customerId:obj.data.customerId,
                        followUserNames:followUserNames,
                        
                  }

                }

              }else if(self.userInfo.data.titleId=='yunwei' && pageName == 'kefuFenPei'){



                msgObj={

                    type: 1,
                    btn: ['转SCRM','不合格'],
                    skin: 'layui-layer-rim', //加上边框
                    area: ['60%', '80%'], //宽高
                    content: $html,
                    title:'沟通信息',
                    shadeClose:true,
                    yes:function(index,layero){

                      var statusId = 1
                      this.parseData['statusId']=statusId
                      self.updateFollowUserName(this.parseData)

                    },
                    btn2:function(index,layero){

                      var statusId = 0
                      this.parseData['statusId']=statusId
                      console.log(this.parseData) 
                      self.updateFollowUserName(this.parseData)
      
                    },
                    parseData:{ 

                          type:'updata_yidu',
                          statusId:statusId,
                          customerId:obj.data.customerId,
                          followUserNames:followUserNames,
                          
                    }

                }

              }else if(self.userInfo.data.titleId=='QC' && pageName == 'kefuFenPei' && obj.data.customer_status !== "1"){

                msgObj={

                  type: 1,
                  btn: ['退回重分配'],
                  skin: 'layui-layer-rim', //加上边框
                  area: ['60%', '80%'], //宽高
                  content: $html,
                  title:'沟通信息',
                  shadeClose:true,
                  yes:function(index,layero){

                    self.QC_chongxinfenpei(obj.data)

                  } 

                }

              }else{

                msgObj={

                  type: 1,
                  btn: [],
                  skin: 'layui-layer-rim', //加上边框
                  area: ['60%', '80%'], //宽高
                  content: $html,
                  title:'沟通信息',
                  shadeClose:true,
                  yes:function(index,layero){

                    var statusId = 1
                    this.parseData['statusId']=statusId
                    self.updateFollowUserName(this.parseData)

                  },
                  btn2:function(index,layero){

                    var statusId = 0
                    this.parseData['statusId']=statusId
                    console.log(this.parseData)
                     
                    self.updateFollowUserName(this.parseData)
    
                  },
                  btn3:function(index,layero){

                    var statusId = 1

                    this.parseData['statusId']=statusId

                    self.QC_updateFollowUserName(this.parseData)
                  },
                  btn4:function(index,layero){

                    var statusId = 0

                    this.parseData['statusId']=statusId

                    self.QC_updateFollowUserName(this.parseData)
                  },
                  parseData:{ 

                        type:'updata_customer_yunweinames_status',
                        statusId:statusId,
                        customerId:obj.data.customerId,
                        followUserNames:followUserNames,
                        
                  }

                }

              }


              //页面层
              self.remarkpage = layer.open(msgObj);

              $(".copytext").click(function(e){
                self.copyTxt(e)
              })

              if(obj.data.customer_status==3){
                 var statusId = 2
                 var parseData ={
                    type:'updata_yidu',
                    statusId:statusId,
                    customerId:obj.data.customerId
                  }
                $.get('../api/api.php',parseData,function(data){
                    console.log(data)
                    self.table.reload('demo')
                }) //更新客服运维表的功能
              }


          })
        },
        updateFollowUserName:function(parseData){ //更新客资状态为 已转单 或 不合格

                var self = this

                var statusId = parseData.statusId

                var followUserNames = parseData.followUserNames

                if(statusId==1){

                    if(followUserNames.length>1){

                        self.alterfollowUserName(followUserNames,function(followUserNamestr){
            
                          parseData['followUserNames']=followUserNamestr

                          $.get('../api/api.php',parseData,function(data){
                              console.log(data)
                              codeStatus(statusId,data)

                              
                          }) //更新客服运维表的功能

                        })
                        


                    }else{

                       parseData['followUserNames']= parseData['followUserNames'][0]
                        $.get('../api/api.php',parseData,function(data){
                              console.log(data)
                              codeStatus(statusId,data)
                              
                        }) //更新客服运维表的功能
                        

                    }

                }else if(statusId==0){


                  //prompt层
                  layer.prompt({title: '请说明不合格的理由', formType: 2}, function(text, index){
                      
                      layer.close(index);
                      parseData['followUserNames']= parseData['followUserNames'][0]
                      parseData['Reasons_for_disqualification']= text
                      parseData['type']= "updata_customer_yunweinames_status"
                      $.get('../api/api.php',parseData,function(data){
                            // console.log(data)
                            codeStatus(statusId,data)
                      }) 

                  })


                }

                function codeStatus(statusId,data){
                  data=JSON.parse(data)
                  if(data.code==300){
                    statusId==2?'':layer.msg('更新成功')
                    
                    self.table.reload('demo')
                    
                  }else if(data.code==400){
                    statusId==2?'':layer.msg('更新失败')

                  }

                  self.layer.close(self.remarkpage)

                }

        },
        QC_updateFollowUserName:function(parseData){ //QC_状态下转单和分配逻辑 和 不合格
            
                console.log(parseData)

                console.log(this.userInfo)

                var self = this

                var statusId = parseData.statusId

                var followUserNames = parseData.followUserNames

                var QCId = this.userInfo.data.userId

                if(statusId==1){

                     self.alteryunweiBox(function(userId,breamk){ //弹出运维弹窗

                       var followUserNamestr = ''

                       if(followUserNames.length>1){

                            self.alterfollowUserName(followUserNames,function(followUserNamestr){  //弹出客服选择弹窗

                              $.get('../api/api.php?type=insertCustomer_yunweinames&customerId='+parseData['customerId']+'&yunweiId='+userId+'&updatetime='+self.nowDate+'&QCId='+QCId + '&followUserName='+followUserNamestr + '&Reasons_for_disqualification='+breamk,function(data){

                                data  = JSON.parse(data)

                                if(data.code == 300 ){

                                  layer.msg('分配成功')

                                  self.table.reload('demo');

                                   

                                }else if(data.code == 400){
                                  layer.msg('分配失败<br>失败原因：'+data.msg)
                                }

                                // layer.close(msgpage)

                                

                              })

                            })

                           

                        }else{


                            followUserNamestr = parseData['followUserNames'][0]

                            $.get('../api/api.php?type=insertCustomer_yunweinames&customerId='+parseData['customerId']+'&yunweiId='+userId+'&updatetime='+self.nowDate+'&QCId='+QCId + '&followUserName='+followUserNamestr + '&Reasons_for_disqualification='+ breamk,function(data){

                                data  = JSON.parse(data)

                                if(data.code == 300 ){

                                  layer.msg('分配成功')

                                  self.table.reload('demo');

                                }else if(data.code == 400){
                                  layer.msg('分配失败<br>失败原因：'+data.msg)
                                }

                                

                            })

                        }

                     })
                    

                }else if(statusId==0){

                  console.log('不合格')

                  self.alterReasons_for_disqualificationBox(function(Reasons_for_disqualification){

                   
                        self.alterfollowUserName(followUserNames,function(followUserNamestr){

                          var parms = {
                            type:"insertCustomer_yunweinames",
                            customerId:parseData['customerId'],
                            updatetime:self.nowDate,
                            QCId:QCId,
                            followUserName:followUserNamestr,
                            Reasons_for_disqualification:Reasons_for_disqualification,
                            customer_status:0
                          }

                          $.get('../api/api.php',parms,function(data){

                                data  = JSON.parse(data)

                                if(data.code == 300 ){

                                  layer.msg('分配成功')
                                  self.table.reload('demo');

                                }else if(data.code == 400){
                                  layer.msg('分配失败<br>失败原因：'+data.msg)
                                }

                                
                            })

                        })

                  })


                }

               

        },
        QC_chongxinfenpei:function(data){ //退回重新分配功能

          // console.log(data)
          var self = this
          var parseData = {
            type:"pass",
            customerId:data.customerId,
            updatedAt:this.nowDate,
          }

          $.get('../api/api.php',parseData,function(data){
                    console.log(data)
                    self.layer.msg('退回成功')
                    self.table.reload('demo')
          }) //更新客服运维表的功能

        },
        alteryunweiBox:function(fun){  //弹出选择运维的弹窗

            $.get('../api/api.php?type=getYunWei',function(data){
                  
                        var data = JSON.parse(data).data

                        console.log(data)

                        var $list = ''

                        for(var i = 0 ;  i < data.length ; i++){

                          $list+=`<div class="layui-inline">
                                    <button class="layui-btn layui-btn-normal kefuIds" style="margin:8px;" data-kefuId = ${data[i]['userId']}>${data[i]['name']}</button>
                                  </div>`
                        

                        }

                        $tableTr=``

                        $.get('../api/api.php?type=getYunWeiFenPeiCount',function(data){

                            data  = JSON.parse(data).data

                            for(var i = 0 ; i < data.length ; i++){
                              
                              $tableTr+=`<tr><th>${data[i].name}</th><th>${data[i].count}</th></tr>`
                            }


                            $table=`

                              <table lay-even lay-skin="line" lay-size="lg" class="layui-table">
                                  <thead>
                                    <tr>
                                      <th>运维姓名</th>
                                      <th>分配数</th>
                                    </tr> 
                                  </thead>
                                  <tbody>
                                    ${$tableTr}
                                  </tbody>
                              </table>


                            `

                            $card=`  
                                  <div class="layui-block">补充内容:</div>
                                  <div class="layui-block">
                                    <textarea name="desc" placeholder="请输入内容" class="layui-textarea breamk" ></textarea>
                                  </div>
                                 `

                            $html=`<div class ="layui-block">
                                    ${$list}
                                  </div>
                                  <div class="layui-block">
                                    ${$card}
                                  </div>
                                  <div class ="layui-block">
                                    ${$table}
                                  </div>
                                  `

                            var element = layui.element;      
                             //页面层
                            var msgpage = layer.open({
                              type: 1,
                              // skin: 'layui-layer-rim', //加上边框
                              area: ['60%', '60%'], //宽高
                              content: $html,
                              title:'客资分配运维'
                            });


                            $(".kefuIds").click(function(e){

                              var userId = $(e.currentTarget).data()['kefuid']

                              var breamk = $(".breamk").val()

                              layer.close(msgpage)

                              fun(userId,breamk)

                            })

                        })


            })
           

        },
        alterfollowUserName:function(followUserNames,fun){   //弹出选择客服归属的弹窗

                $followUserNamesList=''

                for(var i = 0 ; i < followUserNames.length ; i++){
                      
                      $followUserNamesList+=`<button class="layui-btn followUserNamebtn">${followUserNames[i]}</button>`
                }

                followbtn={
                  type:1,
                  content: $followUserNamesList,
                  title:'这个客资是谁的？'
                }

                var followHtml = layer.open(followbtn)

                $('.followUserNamebtn').click(function(e){

                  followUserNamestr = $(e.currentTarget).text()
                  layer.close(followHtml)
                  fun(followUserNamestr)

                })

        },
        alterReasons_for_disqualificationBox:function(fun){ //不合格理由弹出窗

            //prompt层
            layer.prompt({title: '请说明不合格的理由', formType: 2}, function(text, index){

                layer.close(index);

                fun(text)
   
            })

        },
        getbyremark:function(customerId,fun){

          $.get('../api/api.php?type=getbyRemark&customer='+customerId,function(data){

            fun(data)

          })
        },
        download_file:function (data){
          //获取当前域名
          var domain = document.domain + '\\林西项目\\api\\'+data;

          window.location.href = "http://"+domain;
          // download("http://"+domain+"/file.txt","file.txt","text/plain");
        },
        editCheckRowEvent:function(filter){

          var table = layui.table;

          table.on('checkbox('+filter+')', function(obj){ //注：edit是固定事件名，test是table原始容器的属性 lay-filter="对应的值"
                console.log(obj.checked); //当前是否选中状态
                console.log(obj.data); //选中行的相关数据
                console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
          });

        },
        getTableCheck:function(activeBtnId,tableId,fun){ //获取多选框选中行

            var layer =this.layer;
            var self = this;

            $(activeBtnId).click(function(e){

              var table = layui.table;
              var form =  layui.form;
              var checkStatus = table.checkStatus(tableId)
              console.log(checkStatus.data) //获取选中行的数据
              console.log(checkStatus.data.length) //获取选中行数量，可作为是否有选中行的条件
              console.log(checkStatus.isAll ) //表格是否全选
            
              fun(checkStatus)
              
 

            })

        },
        selectKuFu:function(checkStatus){ //选择客服并选中后上传功能模块

              var self =  this
              if(checkStatus.data.length == 0){
                layer.msg('未选中电话')
                return
              }

              $list=''

              $.get('../api/api.php?type=getYunWei',function(data){
                  
                  var data = JSON.parse(data).data

                  console.log(data)

                  for(var i = 0 ;  i < data.length ; i++){

                      $list+=`<div class="layui-inline">
                                <button class="layui-btn layui-btn-normal kefuIds" style="margin:8px;" data-kefuId = ${data[i]['userId']}>${data[i]['name']}</button>
                              </div>`
                  }


                 $html=`<div class ="layui-block">
                    
                          ${$list}
                          
                        <div>`

                   //页面层
                  var msgpage = layer.open({
                    type: 1,
                    // skin: 'layui-layer-rim', //加上边框
                    // area: ['50%', '80%'], //宽高
                    content: $html,
                    title:'客资分配'
                  });


                  $(".kefuIds").click(function(e){

                    userId = $(e.currentTarget).data()['kefuid']

                    for (var i = 0 ; i < checkStatus.data.length; i++) {
                  
                        var checkele = checkStatus.data[i]

                        $.get('../api/api.php?type=insertCustomer_yunweinames&customerId='+checkele['customerId']+'&yunweiId='+userId+'&updatetime='+self.nowDate,function(data){

                            data  = JSON.parse(data)
                            if(data.code == 300 ){
                              layer.msg('分配成功')
                            }else if(data.code == 400){
                              layer.msg('分配失败<br>失败原因：'+data.msg)
                            }

                            layer.close(msgpage)

                            self.table.reload('demo');

                        })
                    }
                  })
              })

        },
        copyTxt:function(e){

            console.log(e.currentTarget.id)

            var Url2=e.currentTarget.innerText;
            var oInput = document.createElement('input');
            oInput.value = Url2;
            document.body.appendChild(oInput);
            oInput.select(); // 选择对象
            document.execCommand("Copy"); // 执行浏览器复制命令
            oInput.className = 'oInput';
            oInput.style.display='none';
            // this.layer.msg('复制成功')
            //小tips
            this.layer.tips('复制成功', '#'+e.currentTarget.id, {
              tips: [1, '#3595CC'],
              time: 400
            });
        },
        loginYanZheng:function(fun){ //登录验证
            layer= this.layer;
            var self  =  this;
            $.get('../api/api.php?type=loginYanZheng',function(data){
              data=JSON.parse(data)
              if (data.code==300){
                layer.msg(data.msg)

                window.location.href = 'signin.html';

              }else if (data.code==400){
                self.userInfo = data
                fun(data)
              }
            })


        },
        loginZhuXiao:function(fun){ //登录注销

          $.get('../api/api.php?type=loginZhuXiao',function(data){
              fun(data);
          })
        }
        

          

       

      }

      window.linxi =linxi

})(window)

    

 

 

